import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:im_app/im/socket/dto/business/Login.dart';
import 'package:im_app/im/socket/dto/business/PullData.dart';
import 'package:im_app/im/socket/service/RpcLoginService.dart';
import 'package:im_app/im/util/ImSingleton.dart';
import 'package:pattern_lock/pattern_lock.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../../util/ImConstant.dart';
import '../../../../util/Md5Util.dart';

class InitPatternLockView extends StatefulWidget{

  final String tenantCode;
  final String loginSuccessUrl;

  const InitPatternLockView({ required this.tenantCode, required this.loginSuccessUrl });

  @override
  State<StatefulWidget> createState() => _InitPatternLockState();

}

class _InitPatternLockState extends State<InitPatternLockView> {

  String _password = '';
  // 设置密码次数
  int _initNum = 0;
  String _errorMsg = '';
  bool _remoteCall = false;

  @override
  Widget build(BuildContext context) {
    return Column(children: [
      Padding(padding: EdgeInsets.only(top: 20, bottom: 10), child: _buildLoginingPane(),),
      SizedBox(
        width: 300,
        height: 300,
        child: PatternLock(
          // color of selected points.
          selectedColor: Colors.blue,
          // radius of points.
          pointRadius: 20,
          // whether show user's input and highlight selected points.
          showInput: true,
          // count of points horizontally and vertically.
          dimension: 3,
          // padding of points area relative to distance between points.
          relativePadding: 0.7,
          // needed distance from input to point to select point.
          selectThreshold: 25,
          // whether fill points.
          fillPoints: true,
          // callback that called when user's input complete. Called if user selected one or more points.
          onInputComplete: (List<int> input) {
            String password = input.join();
            bool isEqual = _password == password;
            print("pattern is $password ${_password}, ${isEqual} , ${_initNum}");
            if (this._password == '') {
              this._password = password;
            }
            if (isEqual) {
              this._initNum++;
            } else {
              this._initNum = 0;
            }
            if (this._initNum >= ImConstant.IM_INIT_PATTERN_LOCK_NUM) {
              this.setPatternLock(password);
            }
          },
        ),
      )
    ],);
  }

  Widget _buildLoginingPane() {
    return Row(children: [
      Visibility(child: SizedBox(width: 30, height: 30, child: CupertinoActivityIndicator(),),
        visible: this._remoteCall,),
      SizedBox(child: Text(this._errorMsg), width: 150,)
    ], mainAxisAlignment: MainAxisAlignment.center,);
  }

  setPatternLock(String password) async {
    RpcLoginService rpcLoginService = new RpcLoginService();

    String userId = ImSingleton.getInstance().session.userId!;
    setState(() {
      this._remoteCall = true;
    });
    String encodePassword = generateMd5(password);
    ResetSlidePasswordReq req = new ResetSlidePasswordReq(userId: userId, password: encodePassword, tenantCode:
      this.widget.tenantCode, terminalType: TerminalType.android.name);
     rpcLoginService.resetSlidePassword(req).then((okResp){
       setPatternLockSettingLabel(userId, encodePassword).then((_){
         setState(() {
           this._remoteCall = false;
         });
         Navigator.of(context).pushNamed(this.widget.loginSuccessUrl);
       }).catchError((onError){
         setState(() {
           this._errorMsg = onError.toString();
         });
       });
     }).catchError((onError){
        setState(() {
          this._errorMsg = onError.toString();
        });
     });
  }

  Future<void> setPatternLockSettingLabel(String userId, String password) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool(ImConstant.IM_PATTERN_LOCK_SETTING, true);
    prefs.setString(ImConstant.IM_PATTERN_LOCK_PASSWORD, password);
    prefs.setString(ImConstant.IM_PATTERN_LOCK_USERID, userId);
  }
}